"use client"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { useState, useEffect } from 'react';
import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table"
import axios from "axios";
import Link from "next/link"

export function Setting() {
  //false 代表card bill true 代表 web3 bill
  const [billingType, setBillingType] = useState(1);
  const [billingName, setBillingName] = useState("Card Billing");
  const [email, setEmail] = useState("")
  const [walletAddress, setWalletAddress] = useState("")
  const [expiryTime, setExpiryTime] = useState("")
  const [balance, setBalance] = useState(0)
  const [web3Bill, setWeb3Bill] = useState([])
  const [stripeBill, setStripeBill] = useState([])
  const [accountBill, setAccountBill] = useState([])
  const [recordNums, setRecordNums] = useState(0)
  const [plan, setPlan] = useState("Free Plan")
  const [isLoading, setIsLoading] = useState(true);
  const [planCancelText, setPlanCancelText] = useState("Cancel Plan")
  const [isVisiblePlanCancelButton, setIsVisiblePlanCancelButton] = useState(false)
  const [cancelStatus, setCancelStatus] = useState(0);


  useEffect(() => {
    getWeb3Billing();
    getUserInfo();
  }, []);

  const cancelPlan = async () => {

    if (cancelStatus == 1) {
      let config = {
        method: 'post',
        maxBodyLength: Infinity,
        url: `${process.env.NEXT_PUBLIC_API_URL}/api/cancelSubscription`,
      };
      axios.request(config)
        .then((response) => {
          setIsLoading(true);
          if (response.data.code == 0) {
            setPlanCancelText("Re-subscribe")
          }
        })
        .catch((error) => {
          setIsLoading(true);
          console.log(error);
        });
    } else if (cancelStatus == 2) {
      let config = {
        method: 'post',
        maxBodyLength: Infinity,
        url: `${process.env.NEXT_PUBLIC_API_URL}/api/updatedSubscription`,
      };
      axios.request(config)
        .then((response) => {
          setIsLoading(true);
          if (response.data.code == 0) {
            setPlanCancelText("Cancel Plan")
          }
        })
        .catch((error) => {
          setIsLoading(true);
          console.log(error);
        });
    }
  }

  async function getWeb3Billing() {
    let config = {
      method: 'get',
      maxBodyLength: Infinity,
      url: `${process.env.NEXT_PUBLIC_API_URL}/api/bill/wallet`,
    };

    axios.request(config)
      .then((response) => {
        for (let i = 0; i < response.data.length; ++i) {
          let str = response.data[i].senderAddress;
          str = str.substring(0, 5) + "****" + str.substring(str.length - 5);
          response.data[i].senderAddress = str;
        }
        setWeb3Bill(response.data)
        setRecordNums(response.data.length)
      })
      .catch((error) => {
        console.log(error);
      });
  }

  async function getStripeBill() {

    let config = {
      method: 'get',
      maxBodyLength: Infinity,
      url: `${process.env.NEXT_PUBLIC_API_URL}/api/bill/stripe`,
    };

    axios.request(config)
      .then((response) => {
        setStripeBill(response.data)
        setRecordNums(response.data.length)
      })
      .catch((error) => {
        console.log(error);
      });
  }

  async function getAccountBill() {

    let config = {
      method: 'get',
      maxBodyLength: Infinity,
      url: `${process.env.NEXT_PUBLIC_API_URL}/api/bill/account`,
    };

    axios.request(config)
      .then((response) => {
        console.log(response.data);
        setAccountBill(response.data);
        setRecordNums(response.data.length);
      })
      .catch((error) => {
        console.log(error);
      });
  }

  function BillDiv() {
    if (billingType == 0) {
      return (
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>invoiceId</TableHead>
              <TableHead>isSuccess</TableHead>
              <TableHead>email</TableHead>
              <TableHead>currency</TableHead>
              <TableHead>amountPaid</TableHead>
              <TableHead>complete time</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {stripeBill.map((item, index) => (
              <TableRow key={index}>
                <TableCell>{item.invoice}</TableCell>
                <TableCell>{item.status ? "success" : "failed"}</TableCell>
                <TableCell>{item.customerEmail}</TableCell>
                <TableCell>{item.currency}</TableCell>
                <TableCell>{item.amountPaid / 100}</TableCell>
                <TableCell>{item.completedAt}</TableCell>
              </TableRow>

            ))}

          </TableBody>
        </Table>

      )
    } else if (billingType == 1) {
      return (
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>txHash</TableHead>
              <TableHead>isSuccess</TableHead>
              <TableHead>senderAddress</TableHead>
              <TableHead>value</TableHead>
              <TableHead>create time</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {web3Bill.map((item, index) => (
              <TableRow key={index}>
                <TableCell>{item.hash}</TableCell>
                <TableCell>{item.isSuccess ? "success" : "failed"}</TableCell>
                <TableCell>{item.senderAddress}</TableCell>
                <TableCell>{item.value / 1000000}</TableCell>
                <TableCell>{item.createdAt}</TableCell>
              </TableRow>

            ))}

          </TableBody>
        </Table>
      )
    } else {
      return (
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Index</TableHead>
              <TableHead>Paid</TableHead>
              <TableHead>Vip Type</TableHead>
              <TableHead>Create Time</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {accountBill.map((item, index) => (
              <TableRow key={index}>
                <TableCell>{index}</TableCell>
                <TableCell>{item.amountPaid}</TableCell>
                <TableCell>{item.paidType == 1 ? "Pro+" : "Unlimited"}</TableCell>
                <TableCell>{item.createdAt}</TableCell>
              </TableRow>

            ))}

          </TableBody>
        </Table>
      )
    }
  }

  const switchBilling = (type) => {
    if (type == 0) {
      // setBillingName("Card Bill")
      getStripeBill()
    } else if (type == 1) {
      // setBillingName("Web3 Wallet Bill")
      getWeb3Billing()
    } else {
      getAccountBill()
    }
    setBillingType(type);

  }

  const getUserInfo = async () => {
    let config = {
      method: 'get',
      maxBodyLength: Infinity,
      url: `${process.env.NEXT_PUBLIC_API_URL}/api/user/info`,
    };

    axios.request(config)
      .then((response) => {
        setEmail(response.data.email)
        setWalletAddress(response.data.walletAddress)
        setBalance(response.data.balance)
        setExpiryTime(response.data.expiryTime.split('T')[0])
        setCancelStatus(response.data.subscriptionStatus)
        //1代表订阅了
        if (response.data.subscriptionStatus == 1) {
          setIsLoading(false);
          setPlanCancelText("Cancel Plan")
          setIsVisiblePlanCancelButton(true)
          //2代表取消了订阅
        } else if (response.data.subscriptionStatus == 2) {
          setIsLoading(false);
          setPlanCancelText("Re-subscribe")
          setIsVisiblePlanCancelButton(true)
        } else {
          //隐藏按钮
          setIsVisiblePlanCancelButton(false);
        }

        if (response.data.vipLevel == 1) {
          setPlan("Pro + Plan");
        }
      })
      .catch((error) => {
        console.log(error);
      });
  }

  return (
    <div className="space-y-8">
      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2 p-4">
          <Label htmlFor="full-name">Email</Label>
          <Input id="full-name" value={email} readOnly />
        </div>
        <div className="space-y-2 p-4">
          <Label htmlFor="solana-wallet">Wallet Address</Label>
          <Input id="solana-wallet" value={walletAddress} readOnly />
        </div>
      </div>
      <div className="flex justify-between">
        <h2 className="text-2xl font-bold">{plan}</h2>
        <h2 className="text-2xl font-bold">ExpiryTime:{expiryTime}</h2>
        {/* <h2 className="text-2xl font-bold">Account Balance {balance / 100} $</h2> */}
        <div className="flex space-x-4">
          {isVisiblePlanCancelButton ?
            <Button disabled={isLoading} onClick={cancelPlan} variant="outline">{planCancelText}</Button> : ""}

          <Link href="/subscribe"><Button>Upgrade Plan</Button></Link>
        </div>
      </div>

      <Button onClick={() => { switchBilling(0) }} variant="outline">Card Bill</Button>
      <Button className="ml-4" onClick={() => { switchBilling(1) }} variant="outline">Web3 Wallet Bill</Button>
      {/* <Button className="ml-4" onClick={() => { switchBilling(2) }} variant="outline">VIP Payment Bill</Button> */}
      <div className="flex justify-between mt-4">
        <span>About {recordNums} results</span>
      </div>
      <div >
        <BillDiv></BillDiv>
      </div>

    </div>
  )
}
